package org.csu.linkgame.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfoenix.controls.JFXToggleButton;
import com.jfoenix.controls.JFXTreeTableColumn;
import com.jfoenix.controls.JFXTreeTableView;
import com.leewyatt.rxcontrols.controls.RXFillButton;
import com.leewyatt.rxcontrols.controls.RXTextField;
import com.leewyatt.rxcontrols.controls.RXTranslationButton;
import com.sun.glass.ui.CommonDialogs;
import de.felixroske.jfxsupport.FXMLController;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.*;
import org.csu.linkgame.domain.User;
import org.csu.linkgame.service.OSSService;
import org.csu.linkgame.service.UserService;
import org.csu.linkgame.utils.AlertView;
import org.csu.linkgame.utils.MD5Utils;
import org.csu.linkgame.utils.ServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.net.URL;
import java.util.*;

@FXMLController
public class UserViewController implements Initializable {

    @FXML
    public RXTextField usernameTextField;
    @FXML
    public RXTextField nicknameTextField;
    @FXML
    public RXTextField userPortTextField;
    @FXML
    public RXTextField passwordTextField;
    @FXML
    public RXTextField userGoalTextField;
    @FXML
    public RXTextField userRankTextField;
    @FXML
    public ComboBox addFriendComboBox;
    @FXML
    public JFXToggleButton isAdminToggleButton;
    @FXML
    public RXFillButton addFriendButton;
    @FXML
    public RXTranslationButton submitButton;
    @FXML
    public RXTranslationButton cancelButton;
    @FXML
    public TreeView<String> friendTree;
    @FXML
    private RXTranslationButton openFileButton;

    private HashMap newUserInfoMap = new HashMap<>();

    private FileChooser fileChooser = new FileChooser();
    File file;
    File dir;
    String userAvatarUrl;
    AlertView alertView;
    String comboBoxSelect;
    TreeItem<String> rootItem = new TreeItem<>();

    private final Node rootIcon = new ImageView(
            new Image(getClass().getResourceAsStream("../images/open_file.png"))
    );

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initComboBox();
        initTreeView();
    }

    private void initComboBox() {
        List<String> usernameList = new ArrayList<>();
        List<User> userList = ServiceUtil.serviceUtil.userService.getAllUserInfo();
        for (User user : userList) {
            usernameList.add(user.getUsername());
        }
        addFriendComboBox.getItems().addAll(usernameList);
        addFriendComboBox.setPlaceholder(new Label("系统玩家获取失败"));
        addFriendComboBox.setEditable(false);
        addFriendComboBox.setPromptText("请选择要添加好友的玩家");
        addFriendComboBox.setVisibleRowCount(5);
        addFriendComboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                comboBoxSelect = newValue;
            }
        });
    }

    private void initTreeView() {
        rootItem = new TreeItem<>("好友列表预览");
        friendTree.setRoot(rootItem);
        // 默认关闭不打开
        rootItem.setExpanded(false);
    }

    public void setTreeViewItem(String friendlist) {
        System.out.println(JSON.parse(friendlist));
        JSONArray list = JSONArray.parseArray(friendlist);
        TreeItem<String> item;
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                item = new TreeItem<>(list.get(i).toString());
                rootItem.getChildren().add(item);
            }
        }
    }

    public void openFileAction(ActionEvent event) {
        if (usernameTextField.getText().equals("")) {
            alertView = new AlertView(Alert.AlertType.WARNING);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("未填写用户名！");
            alertView.setContentText("请填写后再设置头像！！！");
            alertView.showAndWait();
        } else {
            fileChooser.setTitle("请选择作为头像的图片");
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("All Images", "*.*"),
                    new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                    new FileChooser.ExtensionFilter("GIF", "*.gif"),
                    new FileChooser.ExtensionFilter("BMP", "*.bmp"),
                    new FileChooser.ExtensionFilter("PNG", "*.png")
            );

            Stage newUserStage = (Stage) openFileButton.getScene().getWindow();
            file = fileChooser.showOpenDialog(newUserStage);
            if (file != null) {
                dir = new File(file.getParent());
                if (dir.isDirectory()) {
                    fileChooser.setInitialDirectory(dir);
                }
                // 上传至oss云端保存，保存为images/username.jpg
                ServiceUtil.serviceUtil.ossService.upload(file.toString(),"images/" + usernameTextField.getText() + ".jpg");
            }
        }
    }

    public HashMap getUserInfoHashMap() {
        return this.newUserInfoMap;
    }

    public void setUserInfoHashMap(HashMap newUserInfoMap) {
        this.newUserInfoMap = newUserInfoMap;
    }

    public void submitUserInfo(ActionEvent event) {
        if (!usernameTextField.getText().equals("") && !userGoalTextField.getText().equals("") && !userPortTextField.getText().equals("")) {
            alertView = new AlertView(Alert.AlertType.CONFIRMATION);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("你提交新的用户信息！");
            alertView.setContentText("是否提交？请选择！！！");
            Optional<ButtonType> result = alertView.showAndWait();
            if (result.get() == ButtonType.OK) {
                newUserInfoMap.put("username", usernameTextField.getText());
                newUserInfoMap.put("password", passwordTextField.getText());
                newUserInfoMap.put("nickname", nicknameTextField.getText());
                newUserInfoMap.put("isAdmin", isAdminToggleButton.isSelected() ? 1 : 0);
                newUserInfoMap.put("userRank", userRankTextField.getText());
                newUserInfoMap.put("userGoal", userGoalTextField.getText());
                newUserInfoMap.put("userPort", userPortTextField.getText());

                List<String> list = new ArrayList<>();
                for (int i = 0; i < rootItem.getChildren().size(); i++) {
                    list.add(rootItem.getChildren().get(i).getValue());
                }
                newUserInfoMap.put("userFriend", JSONObject.toJSONString(list));
                newUserInfoMap.put("isChange", true);
                Stage newUserStage = (Stage) cancelButton.getScene().getWindow();
                newUserStage.close();
            } else {
                event.consume();
            }
        } else {
            alertView = new AlertView(Alert.AlertType.WARNING);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("信息填写不完整！");
            alertView.setContentText("请仔细检查！！！");
            alertView.showAndWait();
        }
    }

    public void cancel(ActionEvent event) {
        Stage stage = (Stage) cancelButton.getScene().getWindow();
        stage.close();
    }

    public void addNewFriend(ActionEvent event) {
        if (comboBoxSelect != null && !comboBoxSelect.equals(usernameTextField.getText())) {
            alertView = new AlertView(Alert.AlertType.CONFIRMATION);
            alertView.setTitle("管理员请确认！");
            alertView.setHeaderText("是否添加 " + comboBoxSelect + " 作为游戏好友？");
            alertView.setContentText("请做出选择！！！");
            Optional<ButtonType> result = alertView.showAndWait();
            if (result.get() == ButtonType.OK) {
                TreeItem<String> item = new TreeItem<>(comboBoxSelect);
                int oldSize = rootItem.getChildren().size();
                boolean isExist = false;
                for (int i = 0; i < oldSize && !isExist; i++) {
                    isExist = Objects.equals(rootItem.getChildren().get(i).getValue(), comboBoxSelect);
                }
                if (!isExist) {
                    rootItem.getChildren().add(item);
                    int newSize = rootItem.getChildren().size();
                    // 添加成功
                    if (newSize > oldSize) {
                        alertView = new AlertView(Alert.AlertType.INFORMATION);
                        alertView.setTitle("管理员请确认！");
                        alertView.setHeaderText("添加 " + comboBoxSelect + " 作为游戏好友！");
                        alertView.setContentText("添加成功！！！");
                        alertView.showAndWait();
                        rootItem.setExpanded(true);
                    } else {
                        alertView = new AlertView(Alert.AlertType.ERROR);
                        alertView.setTitle("管理员请确认！");
                        alertView.setHeaderText("操作错误");
                        alertView.setContentText("请检查操作！！！");
                        alertView.showAndWait();
                    }
                } else {
                    alertView = new AlertView(Alert.AlertType.WARNING);
                    alertView.setTitle("管理员请确认！");
                    alertView.setHeaderText("操作错误");
                    alertView.setContentText("已拥有该用户作为好友！！！");
                    alertView.showAndWait();
                }
            }
        } else {
            if ( comboBoxSelect != null && comboBoxSelect.equals(usernameTextField.getText())) {
                alertView = new AlertView(Alert.AlertType.WARNING);
                alertView.setTitle("管理员请确认！");
                alertView.setHeaderText("操作错误");
                alertView.setContentText("不可以添加自己为好友！！！");
                alertView.showAndWait();
            } else {
                alertView = new AlertView(Alert.AlertType.WARNING);
                alertView.setTitle("管理员请确认！");
                alertView.setHeaderText("操作错误");
                alertView.setContentText("请先选择好友名字！！！");
                alertView.showAndWait();
            }
        }
    }
}
